import os
import img2pdf
from PIL import Image

Image.MAX_IMAGE_PIXELS = None  # 禁用最大图像尺寸限制

def sort_images_by_name(image_files):
    """
    根据图片名字对图片文件列表进行排序
    """
    return sorted(image_files)

def merge_images_to_pdf(image_folder, output_pdf_path):
    """
    将文件夹中的图片按顺序合并转换为PDF
    """
    output_dir = os.path.dirname(output_pdf_path)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    image_files = []
    for root, dirs, files in os.walk(image_folder):
        for file in files:
            if file.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
                image_files.append(os.path.join(root, file))

    sorted_image_files = sort_images_by_name(image_files)
    if sorted_image_files:
        try:
            with open(output_pdf_path, "wb") as f:
                f.write(img2pdf.convert(sorted_image_files))
            print(f"成功将图片合并转换为 {output_pdf_path}")
        except Exception as e:
            print(f"合并转换为PDF时出错: {e}")
    else:
        print("没有找到有效的图片文件")

if __name__ == "__main__":
    image_folder = "./downloads/img"  # 请替换为实际的图片文件夹路径
    output_pdf_path = "./downloads/pdf/output.pdf"  # 生成的PDF文件路径
    merge_images_to_pdf(image_folder, output_pdf_path)